package com.example.back.service;


import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocketServer {
    // 存储连接的客户端
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    // 与客户端的连接会话
    private Session session;

    // 当前连接用户ID
    private String userId;

    // 连接建立成功调用的方法
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        webSocketMap.put(userId, this);
        System.out.println("用户" + userId + "连接成功，当前在线人数：" + webSocketMap.size());
    }

    // 连接关闭调用的方法
    @OnClose
    public void onClose() {
        webSocketMap.remove(userId);
        System.out.println("用户" + userId + "断开连接，当前在线人数：" + webSocketMap.size());
    }

    // 收到客户端消息后调用的方法
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到用户" + userId + "的消息：" + message);
        // 可以在这里处理消息并转发
    }

    // 发生错误时调用
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    // 发送消息
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    // 群发消息
    public static void sendToAll(String message) throws IOException {
        for (WebSocketServer item : webSocketMap.values()) {
            item.sendMessage(message);
        }
    }

    // 向指定用户发送消息
    public static void sendToUser(String userId, String message) throws IOException {
        WebSocketServer user = webSocketMap.get(userId);
        if (user != null) {
            user.sendMessage(message);
        }
    }
}